
import 'dart:ui_web';

import 'package:js/js.dart';
import 'package:flutter/material.dart';
import 'dart:html' as html;

// // JS 交互方法
@JS('updateTooltip')  // 对应 JS 中的函数名称
external void updateTooltip(String city, String newText);

void _updateTooltip(String city, String text) {
  print("updateTooltip called with city: $city, text: $text");
  updateTooltip(city, text);  // 调用 JS 方法
}

class ChinaMapPage extends StatefulWidget {
  const ChinaMapPage({super.key});

  @override
  _ChinaMapPageState createState() => _ChinaMapPageState();
}

class _ChinaMapPageState extends State<ChinaMapPage> {
  final String iframeId = "iframe-custom"; // iframe 唯一 ID

  @override
  void initState() {
    super.initState();

    registerViewFactories();
    Future.delayed(Duration(seconds: 4), () {
      // _updateTooltip("广东", "人口：2200万");
      sendMessageToIframe("广东", 1500);
    });
  }

  void registerViewFactories() {
    // 注册自定义 HTML 元素视图工厂
    // 这个工厂用于生成一个 iframe
    platformViewRegistry.registerViewFactory(
      iframeId, // 视图类型名
          (int viewId) {
        final html.IFrameElement iframe = html.IFrameElement()
          ..src = "local_map.html"  // 你要嵌入的 HTML 页面地址
        // ..style.border = 'none'
        // ..width = "50%"
        // ..height = "50%"
            ;

        return iframe;
      },
    );
  }


  void sendMessageToIframe(String city, int value) {
    print("sendMessageToIframe called with city: $city, text: $value");
    final html.IFrameElement? iframe =
    html.document.querySelector('iframe') as html.IFrameElement?;
    iframe?.contentWindow?.postMessage({
      'city': city,
      'newText': value
    }, '*'); // Post message to iframe
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("全国地图")),
      body: HtmlElementView(viewType: iframeId),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _updateTooltip("广东", "人口：2200万");
        },
        child: const Text('北京北京北京'),
      ),
    );
  }
}
